﻿var gonzales = function () {
    var execute = function (f, context, outputspan) {
        if (typeof (f.func) == "function") {

            if (f.preparation != null && typeof (f.preparation) == "function") {
                f.preparation();
            }

            for (var c = 0; c < f.count; c++) {
                var start = new Date();
                f.func();
                var end = new Date();
                f.total += (end - start);
            }

            outputspan.innerHTML = f.name + ": <b>" + f.total + "ms / " + f.count + " = " + (f.total / f.count) + "ms</b>";

            if (context.div != null)
                context.div.appendChild(document.createElement("br"));
        }
        else {
            throw "Error: " + fs[x].name;
        }

        setTimeout(function () { context.start(context); }, 1);
    }

    var _start = function (context) {
        lastfunction++;
        var outputspan;
        if (lastfunction < fs.length) {
            outputspan = document.createElement("span");
            outputspan.innerHTML = fs[lastfunction].name + ": running...";
            if (context.div != null)
                context.div.appendChild(outputspan)

            fs[lastfunction].total = 0;
            setTimeout(function () { execute(fs[lastfunction], context, outputspan) }, 1);


        }
        else {
            lastfunction = -1;
            if (context.div != null) {
                outputspan = document.createElement("span");
                outputspan.innerHTML = "--- End ---";
                context.div.appendChild(outputspan)
                context.div.appendChild(document.createElement("br"));
            }
        }
    }

    var fs = [];
    var lastfunction = -1;
    var total = 0;


    this.start = function () {
        _start(this);
    };

    this.div = null;

    this.addFunction = function (name, func, count, preparation) {
        fs.push({ "name": name, "func": func, "count": count, "total": 0, "preparation": preparation });
    };
};